package cn.xshi.oauth.client.timer;

import cn.hutool.core.collection.CollectionUtil;
import cn.xshi.common.base.BaseResult;
import cn.xshi.common.base.InitBean;
import cn.xshi.common.util.RestTemplateUtil;
import cn.xshi.common.util.StringUtil;
import cn.xshi.oauth.client.constant.Constant;
import cn.xshi.oauth.client.util.HeartbeatAttributesUtil;
import cn.xshi.oauth.client.util.SysModeAttributesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
 * @Desc Pull 密钥 是否合理
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
@Slf4j
public class SysModePullScheduled {

    @Resource
    RestTemplateUtil restTemplateUtil;

    @Resource
    InitBean initBean;

    @Resource
    SysModeAttributesUtil sysModeAttributesUtil;

    @Resource
    HeartbeatAttributesUtil heartbeatAttributesUtil;

    @Scheduled(cron="*/30 * * * * *")
    public void execute() {
        try {
           if(heartbeatAttributesUtil.isConnected()){
               pull();
           }else{
               log.error("无法连接授权中心...");
           }
        }catch (Exception e){
            log.error("验证密钥失败，信息：{}",e);
        }
    }


    public void pull(){
        Map<String,String> attributes = sysModeAttributesUtil.getAttributes();
        String jehcCloudKey = initBean.getJehcCloudKey();
        String jehcCloudSecurity = initBean.getJehcCloudSecurity();
        if(CollectionUtil.isEmpty(attributes)){
            if(StringUtil.isEmpty(jehcCloudKey)){
                log.error("平台密钥Key为空...");
                return;
            }
            if(StringUtil.isEmpty(jehcCloudSecurity)){
                log.error("平台密钥为空...");
                return;
            }
            BaseResult baseResult = null;
            try {
                Map<String,String> map = new HashMap<>();
                map.put("jehcCloudKey",jehcCloudKey);
                map.put("jehcCloudSecurity",jehcCloudSecurity);
                baseResult = restTemplateUtil.post(restTemplateUtil.restOauthURL() + "/signature",BaseResult.class,map);
            }catch (Exception e){
                log.error("验签密钥失败. 信息:{}",e);
            }
            if(null == baseResult){
                log.error("The jehcCloudKey OR jehcCloudSecurity is not invalid");
                return;
            }
            if(!baseResult.getSuccess()){
                log.error("验证密钥失败...");
                return;
            }
            sysModeAttributesUtil.put(Constant.SYS_MODE_KEY,Constant.SYS_MODE_KEY);
            log.info("验证密钥成功...");
        }
    }
}
